<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/14 0014
 * Time: 上午 9:39
 */
namespace app\member\controller;
use app\common\api\member\IEmail;
use app\member\model\Member;
use app\member\validate\Vali_email;
use app\member\validate\Vali_mem;
use app\member\validate\ValidateFun;

class Email implements IEmail{
    //获取参数
    private $data=[];
    /**
     * 初始化参数
     * Email constructor.
     */
    public function __construct(array $config=[])
    {
        $this->data=array_filter_full(array_merge($this->data,$config));
    }

    /**
     * 邮箱登录
     * @return array
     */
    public function login(){
        $data = $this->data;

        $vali_data = Vali_mem::_emailLogin(); #获取验证规则
        $validate = new ValidateFun($vali_data['rule'], $vali_data['message']);#实例化验证类
        //规则验证
        if(!$validate->check($data)){
            return ['code'=>$validate->getError(),'msg'=>config('msg.'.$validate->getError())];
        }

        $model = new Member();#用户model
        $res = $model->login($data);

        #插入登录日志
        $d = [
            'uid'   => $res['id'],
            'lasttime'=>date('Y-m-d H:i:s'),
            'lastip'    =>get_ip(),
            'status'    =>1,
            'del'       =>1
        ];
        $model->login_log($d);
        return ['code'=>200,'msg'=>config('msg.200'),'data'=>$res];
    }

    /**
     * 邮箱注册
     * @return array
     */
    public function register(){
        $data = $this->data;
        $vali_data = Vali_mem::_email(); #获取验证规则
        $validate = new ValidateFun($vali_data['rule'], $vali_data['message']);#实例化验证类
        if(!$validate->check($data)){
            $err=$validate->getError();
            return ['code'=>$err,'msg'=>config("msg.{$err}")];
        }

        $data['password'] = !empty($data['password']) ? $data['password'] : '123456';
        $data['encrypt']  = getCode(6,3);
        //账号为空，生成一个随机账号
        if(empty($data['username'])){
            $data['username'] = createUsername();#生成账号
            $data['password'] = getMd5($data['password'],$data['username'],$data['encrypt']);
        }else{
            $data['password'] = getMd5($data['password'],$data['username'],$data['encrypt']);
        }

        $model = new Member();
//        \app\common\controller\Log::addlog(['msg'=>'邮箱用户注册']);#添加系统日志
        $result = $model->mem_add($data);
        if ($result>0){
            return ['code'=>200,'msg'=>config('msg.200')];
        }else{
            return ['code'=>10006,'msg'=>config('msg.10006')];
        }
    }
}